import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/ecycommon/EcyRequestBaseManager.dart';
import 'package:ecy_app_flutter/routes/my/model/OrderCommentDto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../model/EcyApiCommonResponse.dart';
import '../model/EcyMyOrderCommodity.dart';

class EcyOrderEvaluatePage extends StatefulWidget {
  EcyMyOrderCommodity commodity;

  EcyOrderEvaluatePage({required super.key, required this.commodity});

  @override
  _EcyOrderEvaluatePageState createState() => _EcyOrderEvaluatePageState();
}

class _EcyOrderEvaluatePageState extends State<EcyOrderEvaluatePage> {
  _EcyOrderEvaluatePageState();

  List<double> ratingList = [5.0, 5.0, 5.0, 5.0];
  List<String> evaluateTitleList = ["完美无暇", "发货及时", "店家诚信", "售后服务"];
  final TextEditingController _evaluateController = TextEditingController();
  int _evaluateLength = 0;
  bool _isButtonDisabled = false;
  bool _loading = false;

  @override
  void initState() {
    super.initState();
    _loadEvaluateDetail();

    _evaluateController.addListener(() {
      setState(() {
        _evaluateLength = _evaluateController.text.length;
      });
    });
  }

  _loadEvaluateDetail() async {
    if (widget.commodity.evaluateId != null) {
      var response =
          await EcyRequestbasemanager().get("/app/api/app/order/comment/detail/${widget.commodity.evaluateId}", {});
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          OrderCommentDto orderCommentDto = OrderCommentDto.fromJson(response["data"]);
          setState(() {
            _evaluateController.text = orderCommentDto.comment ?? "";
            ratingList = [
              orderCommentDto.flawlessStar ?? 5.0,
              orderCommentDto.shippingStar ?? 5.0,
              orderCommentDto.storeIntegrityStar ?? 5.0,
              orderCommentDto.saleServiceStar ?? 5.0
            ];
          });
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试", duration: const Duration(seconds: 2));
        }
      }
    }
  }

  _submitEvaluate() async {
    if (_loading) {
      return;
    }

    try {
      setState(() {
        _loading = true;
      });

      // if (_evaluateController.text.trim().isEmpty) {
      //   EasyLoading.showToast("说说您的感受吧", duration: const Duration(seconds: 2));
      //   return;
      // }

      var commodity = widget.commodity;
      OrderCommentDto orderCommentDto = OrderCommentDto();
      orderCommentDto.orderId = commodity.orderId;
      orderCommentDto.skuId = commodity.id;
      orderCommentDto.flawlessStar = ratingList[0];
      orderCommentDto.shippingStar = ratingList[1];
      orderCommentDto.storeIntegrityStar = ratingList[2];
      orderCommentDto.saleServiceStar = ratingList[3];
      orderCommentDto.comment = _evaluateController.text.trim();
      orderCommentDto.shopId = commodity.shopId;

      var response = await EcyRequestbasemanager().post("/app/api/app/order/comment/save", orderCommentDto);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("评价成功", duration: const Duration(seconds: 2));
          var currOrderComment = OrderCommentDto.fromJson(response["data"]);
          setState(() {
            commodity.evaluateId = currOrderComment.id;
            _evaluateController.text = currOrderComment.comment ?? "";
          });
          Navigator.pop(context, commodity);
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试", duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    var evaluatedFlag = widget.commodity.evaluateId == null;

    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        scrolledUnderElevation: 0,
        title: Text(
          '评价',
          style: TextStyle(
              fontFamily: "PingFang SC", fontWeight: FontWeight.w700, fontSize: 16.sp, color: const Color(0xFF262626)),
        ),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            //触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Card(
                  color: Colors.white,
                  child: Padding(
                      padding: const EdgeInsets.only(left: 15, top: 15, right: 15, bottom: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: 80.w,
                                width: 80.w,
                                child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8.r),
                                    child: CachedNetworkImage(
                                        width: 80.w,
                                        height: 80.w,
                                        imageUrl: widget.commodity.image ?? "",
                                        imageBuilder: (context, imageProvider) => Container(
                                              decoration: BoxDecoration(
                                                  borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                                  image: DecorationImage(image: imageProvider, fit: BoxFit.cover)),
                                            ),
                                        errorWidget: (context, url, error) => Image.asset(
                                              "assets/images/app_icon.png",
                                              width: 80.w,
                                              height: 80.w,
                                            ))),
                              ),
                              Expanded(
                                  child: Padding(
                                padding: const EdgeInsets.only(left: 6),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(widget.commodity.commodityName ?? "",
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w700,
                                            fontSize: 14.sp,
                                            color: const Color(0xFF262626)),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis),
                                    const Padding(padding: EdgeInsets.only(bottom: 2)),
                                    Text(widget.commodity.name ?? "",
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 12.sp,
                                            color: const Color(0xFF8C8C8C)),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis),
                                    const Padding(padding: EdgeInsets.only(bottom: 15)),
                                    Row(
                                      children: [
                                        Expanded(
                                          flex: 1,
                                          child: Text(
                                            '￥${widget.commodity.price ?? 0.00}',
                                            style: TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontWeight: FontWeight.w900,
                                                fontSize: 14.sp,
                                                color: const Color(0xFFF55F4E)),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 3,
                                          child: Align(
                                            alignment: Alignment.centerRight,
                                            child: Text(
                                              'x${widget.commodity.num ?? 0}',
                                              style: TextStyle(
                                                  fontFamily: "PingFang SC",
                                                  fontWeight: FontWeight.w500,
                                                  fontSize: 12.sp,
                                                  color: const Color(0xFF8C8C8C)),
                                            ),
                                          ),
                                        ),
                                      ],
                                    )
                                  ],
                                ),
                              )),
                            ],
                          ),
                        ],
                      )),
                ),
                const Padding(padding: EdgeInsets.only(bottom: 3)),
                Card(
                  color: Colors.white,
                  child: Padding(
                      padding: const EdgeInsets.all(15),
                      child: Column(children: [
                        ...evaluateTitleList.map((title) {
                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            child: Row(spacing: 8, children: [
                              Expanded(
                                flex: 1,
                                child: Text(
                                  title,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 14.sp,
                                      color: const Color(0xFF8C8C8C)),
                                ),
                              ),
                              Expanded(
                                flex: 4,
                                child: RatingBar.builder(
                                  initialRating: ratingList[evaluateTitleList.indexOf(title)],
                                  ignoreGestures: !evaluatedFlag,
                                  minRating: 1,
                                  direction: Axis.horizontal,
                                  allowHalfRating: true,
                                  itemCount: 5,
                                  itemSize: 28,
                                  itemPadding: const EdgeInsets.symmetric(horizontal: 4.0),
                                  itemBuilder: (context, _) => const Icon(
                                    Icons.star,
                                    color: Colors.amber,
                                  ),
                                  onRatingUpdate: (rating) {
                                    ratingList[evaluateTitleList.indexOf(title)] = rating;
                                  },
                                ),
                              ),
                            ]),
                          );
                        }),
                        Stack(children: [
                          TextField(
                              controller: _evaluateController,
                              maxLines: 4,
                              maxLength: 500,
                              enabled: evaluatedFlag,
                              maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds,
                              keyboardType: TextInputType.multiline,
                              decoration: InputDecoration(
                                counterText: '',
                                hintText: "说说您的感受吧",
                                hintStyle: const TextStyle(
                                  color: Colors.grey,
                                ),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(5),
                                  borderSide: BorderSide.none,
                                ),
                                //是否填充背景色
                                filled: true,
                                //设置背景色，filled 为 true 时生效
                                fillColor: const Color(0xFFF5F5F5),
                                contentPadding: const EdgeInsets.all(10.0),
                              )),
                          Positioned(
                            bottom: 5, // 调整这个值来改变位置
                            right: 10, // 调整这个值来改变位置
                            child: Text('$_evaluateLength/500',
                                style: const TextStyle(
                                  color: Colors.grey,
                                )),
                          )
                        ]),
                        const Padding(padding: EdgeInsets.only(bottom: 15)),
                        if (evaluatedFlag)
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: 40.0,
                                  padding: const EdgeInsets.only(left: 10),
                                  child: TextButton(
                                      onPressed: () {
                                        _submitEvaluate();
                                      },
                                      style: ButtonStyle(
                                        alignment: Alignment.center,
                                        backgroundColor: WidgetStatePropertyAll(
                                            _isButtonDisabled ? const Color(0xFFffc0cb) : const Color(0xFFEA4B9B)),
                                        foregroundColor: const WidgetStatePropertyAll(Colors.white),
                                      ),
                                      child: const Text(
                                        '提交评价',
                                        style: TextStyle(
                                          height: 1,
                                          fontSize: 18,
                                          leadingDistribution: TextLeadingDistribution.even, // 设置leading策略
                                        ),
                                      )),
                                ),
                              )
                            ],
                          )
                      ])),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
